﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Scale2;
using System.IO.Ports;
using System.Text.RegularExpressions;
using ECS.Framework;
using ECS.DAL;
using ECS.DAL.Component;
using ECS.DAL.Entity;
using System.Threading;

namespace E_ICS
{
    public partial class Weight : Form
    {
        #region private properties
        string reg = @"^[0-9\b]*$";
        int Gross = 0;
        int Net = 0;
        int Tare = 0;
        int Pallet = 0;
        //int Weighting = 0;
        string test = "";
        string aa = "";
        Double resutl = 0;
       // GlobalVariable get = new GetScale();
        Main.frmMain2 main;
        #endregion

        #region form event
        //SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["con3"].ConnectionString);
        public Weight(Main.frmMain2 _main)
        {
            InitializeComponent();
            main = _main;
        }
        private void Weight_Load(object sender, EventArgs e)
        {
            try
            {
                default_tare_weight();
                get_com_port();

                //why read weight status is on OnPaint event??? it impact form responsive performance.
                //because it always call this method.
                ReadWeightStatus();
            }
            catch
            {

                // throw;
            }
            //txtGross.Focus();

        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            btnSaveWeight();
            timer1.Enabled = false;
            //Wgh = new GetScale();


        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            //Wgh = new GetScale();
            this.Dispose();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1Click();


        }
        private void txtNet_TextChanged(object sender, EventArgs e)
        {

            if (String.IsNullOrEmpty(txtNet.Text))
            {
                int chknet = Net;
                if (chknet <= 0)
                {
                    btnSave.Enabled = false;
                }
                else
                {
                    btnSave.Enabled = true;
                }
            }
            else
            {
                int chknet = Net;
                if (chknet >= 1)
                {
                    btnSave.Enabled = true;
                }
                else
                {
                    btnSave.Enabled = false;
                }
                //btnSave.Enabled = true;
            }
        }
        private void panel1_Paint(object sender, PaintEventArgs e)
        {
            //remark for question
            //ReadWeightStatus();
        }
        private void txtPallet_TextChanged(object sender, EventArgs e)
        {
            CelWeight(txtPallet.Text, txtGross.Text);
            if (resutl > 0)
            {
                btnSave.Enabled = true;
                // btnSave.Focus();
            }
        }

        private void txtGross_TextChanged(object sender, EventArgs e)
        {
            CelWeight(txtPallet.Text, txtGross.Text);
            if (resutl > 0)
            {
                btnSave.Enabled = true;
                // btnSave.Focus();
            }
        }

        string ta = "";
        private DateTime value;

        private void txtTare_KeyPress(object sender, KeyPressEventArgs e)
        {
            //if (!(char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back)))
            //{
            //    e.Handled = true;
            //}
            try
            {
                if (!(Regex.IsMatch(e.KeyChar.ToString(), reg)))
                {
                    e.Handled = true;
                }
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }   
        }

        //private void CheckTab(Keys p)
        //{
        //   // throw new NotImplementedException();
        //}

        private void CelWeightTare_KeyPress(string p, string g, string t)
        {
            try
            {
                if (p.Equals(string.Empty)
               || g.Equals(string.Empty))
                {
                    //
                }
                else
                {
                    int pallet = Convert.ToInt32(p);
                    Double gross = Convert.ToInt64(g);
                    Double _tare = Convert.ToInt64(t);





                    resutl = 0;
                    Double mul = 0;

                    mul = 1 * _tare;
                    resutl = gross - mul;


                    txtTare.Text = String.Format("{0:#,##0}", mul);
                    txtNet.Text = String.Format("{0:#,##0}", resutl);
                }
            }
            catch
            {

                // throw;
            }
        }

        private void txtPallet_KeyPress(object sender, KeyPressEventArgs e)
        {
            //if (!(char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back)))
            //{
            //    e.Handled = true;
            //}
            try
            {
                if (!(Regex.IsMatch(e.KeyChar.ToString(), reg)))
                {
                    e.Handled = true;
                }
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }       
        }

        private void txtGross_KeyPress(object sender, KeyPressEventArgs e)
        {
            //if (!(char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back)))
            //{
            //    e.Handled = true;
            //}
            try
            {
                if (!(Regex.IsMatch(e.KeyChar.ToString(), reg)))
                {
                    e.Handled = true;
                }
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }       
        }
        #endregion

        #region private methods
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            bool baseResult = base.ProcessCmdKey(ref msg, keyData);
            if (keyData == (Keys.F1))
            {

                button1Click();
                return true;
            }
            else if (keyData == (Keys.LButton | Keys.ShiftKey | Keys.Control))
            {
                btnSaveWeight();
                return true;
            }

            else if (keyData == (Keys.Escape))
            {

                this.Close();
            }
            else if (keyData == Keys.Tab && txtTare.Focused)
            {
                //getTare(txtPallet.Text);
                // txtGross.Focus();
                // MessageBox.Show("sss");
                CelWeightTare_KeyPress(txtPallet.Text, txtGross.Text, txtTare.Text);
                if (resutl > 0)
                {
                    btnSave.Enabled = true;
                    // btnSave.Focus();
                }
                btnSave.Focus();
                return true;
            }


            return baseResult;
        }
        private void btnSaveWeight()
        {

            string gross = txtGross.Text;
            string tare = txtTare.Text;
            string net = txtNet.Text;
            string pallet = txtPallet.Text;
            string time = string.Format("{0:dd/MM/yyyy HH:mm:ss}", DateTime.Now);
            //string weightCount = "";
            //Weighting = Weighting + 1;
            //weightCount = Weighting.ToString();



            if (gross != string.Empty && tare != string.Empty && net != string.Empty)
            {
                //btnSave.Enabled = true;
                string[] array = new string[5] { pallet, gross, tare, net, time };
                main.GetDataFromWeightDisplay(array);

                this.Dispose();

            }

            // Wgh = null;
        }
        private void button1Click()
        {
            
            try
            {
                //  string TempWeig = "";
                // GlobalVariable.Wgh = new GetScale();
                try
                {
                    //serialPort1.PortName = GlobalVariable.WghComPort;
                    //serialPort1.ReadTimeout = 500;
                    //serialPort1.Open();
                    txtGross.Text = String.Format("{0:0.##}", Convert.ToInt32(GlobalVariable.Wgh.GetFromPort(GlobalVariable.WghComPort)));
                    //String.Format("{0:0.##}", Convert.ToInt32(getRawWeight()));
                    //  String.Format("{0:0.##}", Convert.ToInt32(GlobalVariable.Wgh.GetFromPort(GlobalVariable.WghComPort)));
                }
                catch (Exception)
                {

                    // throw;
                }



            }
            catch (Exception)
            {

                //throw;
            }
            finally
            {

               // this.Dispose();
            }

        }



        private void ReadWeightStatus()
        {
            EicsSetupComponent comp = new EicsSetupComponent();
            EicsSetup param = new EicsSetup();
            param.Device = GlobalVariable.user.Device;
            param.AppId = GlobalVariable.user.ApplicationID;
            param.UserId = GlobalVariable.user.UserID;
            List<ObjectContext> items = comp.Search(param);
            if (items != null && items.Count > 0)
            {
                foreach (ObjectContext item in items)
                {
                    if ((((EicsSetup)item).SetupType == "STATION") && (((EicsSetup)item).StationId == GlobalVariable.user.Device))
                    {
                        if (((EicsSetup)item).ValueString == "NO")
                        {
                            btnReadWeight.Enabled = false;
                            txtGross.ReadOnly = false;
                        }
                        else if (((EicsSetup)item).ValueString == "YES")
                        {
                            btnReadWeight.Enabled = true;
                            txtGross.ReadOnly = true;
                        }
                        else if (((EicsSetup)item).ValueString == "BOTH")
                        {
                            btnReadWeight.Enabled = true;
                            txtGross.ReadOnly = false;
                        }
                        break;
                    }
                }
            }
            //SqlCommand cmd = new SqlCommand("SELECT * from t_eics_setup WHERE type='STATION'", sqlCon);

            //SqlDataAdapter daversion = new SqlDataAdapter(cmd);

            //sqlCon.Open();
            //SqlDataReader reader2 = cmd.ExecuteReader();

            //if (reader2.Read())
            //{
            //    string status = reader2["setting_value_string"].ToString();

            //    if (status.Equals("NO"))
            //    {
            //        btnReadWeight.Enabled = false;
            //    }

            //    else if (status.Equals("YES"))
            //    {
            //        btnReadWeight.Enabled = true;
            //    }
            //}

            //else
            //{
            //    //return null;
            //}
            //sqlCon.Close();
        }

        private void CelWeight(string p, string g)
        {
            try
            {
                if (p.Equals(string.Empty)
               || g.Equals(string.Empty))
                {
                    //
                }
                else
                {
                    int pallet = Convert.ToInt32(p);
                    Double gross = Convert.ToInt64(g);





                    resutl = 0;
                    Double mul = 0;

                    mul = pallet * Tare;
                    resutl = gross - mul;


                    txtTare.Text = String.Format("{0:#,##0}", mul);
                    txtNet.Text = String.Format("{0:#,##0}", resutl);
                }
            }
            catch
            {

                // throw;
            }


        }
        private void default_tare_weight()
        {
            try
            {
                string default_tare_weight = "";
                EicsSetupComponent comp = new EicsSetupComponent();
                EicsSetup param = new EicsSetup();
                param.Device = GlobalVariable.user.Device;
                param.AppId = GlobalVariable.user.ApplicationID;
                param.UserId = GlobalVariable.user.UserID;
                List<ObjectContext> items = comp.Search(param);
                if (items != null && items.Count > 0)
                {
                    foreach (ObjectContext item in items)
                    {
                        if (((EicsSetup)item).SettingName == "DEFAULT_TARE")
                        {
                            default_tare_weight = ((EicsSetup)item).ValueNumber.ToString();
                            txtTare.Text = default_tare_weight;
                            Tare = Convert.ToInt32(default_tare_weight);
                            break;
                        }
                    }
                }

                //SqlCommand cmd = new SqlCommand("SELECT setting_value_number FROM t_eics_setup Where setting_name = 'DEFAULT_TARE'", sqlCon);
                //SqlDataAdapter DA = new SqlDataAdapter(cmd);
                //sqlCon.Open();
                //SqlDataReader reader3 = cmd.ExecuteReader();
                //if (reader3.Read())
                //{
                //    default_tare_weight = reader3["setting_value_number"].ToString();
                //    txtTare.Text = default_tare_weight;
                //    Tare = Convert.ToInt32(default_tare_weight);
                //}
                //else
                //{
                //    sqlCon.Close();
                //}
                //sqlCon.Close();
            }
            catch
            {

                // throw;
            }
            //txtGross.Focus();

        }

        private void get_com_port()
        {
            try
            {
                //string default_tare_weight = "";
                EicsSetupComponent comp = new EicsSetupComponent();
                EicsSetup param = new EicsSetup();
                param.Device = GlobalVariable.user.Device;
                param.AppId = GlobalVariable.user.ApplicationID;
                param.UserId = GlobalVariable.user.UserID;
                List<ObjectContext> items = comp.Search(param);
                if (items != null && items.Count > 0)
                {
                    foreach (ObjectContext item in items)
                    {
                        if (((EicsSetup)item).SettingName == "SCALE_PORT" && ((EicsSetup)item).StationId == GlobalVariable.user.Device)
                        {
                            GlobalVariable.WghComPort = ((EicsSetup)item).ValueString;
                            break;
                        }
                    }
                }

                //SqlCommand cmd = new SqlCommand("select setting_value_string from t_eics_setup WHERE setting_name='SCALE_PORT' and Station_id=@Station1", sqlCon);
                //cmd.Parameters.AddWithValue("@Station1", GlobalVariable.Device);
                //SqlDataAdapter DA = new SqlDataAdapter(cmd);
                //sqlCon.Open();
                //SqlDataReader reader3 = cmd.ExecuteReader();
                //if (reader3.Read())
                //{
                //    GlobalVariable.WghComPort = reader3["setting_value_string"].ToString();

                //}
                //else
                //{
                //    sqlCon.Close();
                //}
                //sqlCon.Close();
            }
            catch
            {

                // throw;
            }
            //txtGross.Focus();

        }
        #endregion


        //  private void getnet(string gross)
        //{

        //    Tare = int.Parse(txtTare.Text);
        //    if (txtGross.Text != String.Empty)
        //    {
        //        if (gross != String.Empty)
        //        {
        //            Gross = int.Parse(gross);
        //        }
        //        else
        //        {
        //            gross = txtGross.Text;
        //            Gross = int.Parse(gross);
        //        }

        //    }
        //    Net = Gross - Tare;
        //    txtNet.Text = Net.ToString();
        //}
        //private void txtGross_TextChanged(object sender, EventArgs e)
        //{
        //    getnet();
        //}






        

        //private void timer1_Tick(object sender, EventArgs e)
        //{
            
        //}

        public double getRawWeight()
        {
            double w = 0.0;
            try
            {
                if (serialPort1.IsOpen)
                {
                    serialPort1.Close();
                }
               // else
               // {
                    serialPort1.PortName = GlobalVariable.WghComPort;
                    serialPort1.Open();
               // }
               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return 0;
               // throw;
            }
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
           // w = -1;
          //  serialPort1.Write("W");
            Thread.Sleep(1000);
            try
            {
                w = (Convert.ToDouble(weg.Substring(1, 5)) / 1000);
            }
            catch (Exception)
            {

                MessageBox.Show("Error in measuring the weight");
            }
            return w;
        }
        //string value = ""; 
        private void timer1_Tick_1(object sender, EventArgs e)
        {
           

        }

        string weg = "";
           
        public void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                int length = serialPort1.BytesToRead;
                if (length > 0)
                {
                    try
                    {
                        weg = serialPort1.ReadExisting();
                    }
                    catch (Exception)
                    {

                        // throw;
                    }
                }
               
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
            finally
            {
                serialPort1.Close();
                serialPort1.Dispose();
            }
        }

        private void Weight_FormClosing(object sender, FormClosingEventArgs e)
        {
            serialPort1.Close();
            serialPort1.Dispose();
        }










    }


  
}
